# -*- encoding: utf-8 -*-
from odoo import fields, models
import akshare as ak


class CovProvinceStatistics(models.Model):
    _name = 'cov.province.statistics'
    _description = '中国疫情分省份统计'
    _rec_name = 'province'
    _order = 'total'

    province = fields.Many2one('res.country.state', domain=[('country_id', '=', 48)], string='省份')
    total = fields.Integer(string='累计确诊')
    state_code = fields.Char(related='province.code', string='简称', store=True)

    def get_cov_regions_data(self):
        """
        自动任务获取各省份的数据
        :return:
        """
        covid_19_163_df = ak.covid_19_163(indicator="中国各地区累计数据")
        to_create = []
        self_record = self.search([])
        self_record_dict = dict(list(map(lambda r: (r.province.name, r.id), self_record)))
        for inx in covid_19_163_df.index:
            value = covid_19_163_df.loc[inx][0]
            pros = self.env['res.country.state'].search([('name', 'ilike', inx)])
            if not pros:
                continue
            vals = {'province': pros[-1].id, 'total': value}
            self_r_id = self_record_dict.get(pros[-1].name, False)
            if self_r_id:
                self_r = self.browse(self_r_id)
                self_r.write(vals)
            else:
                to_create.append(vals)
        self.create(to_create)
